import pygame
import math
from settings import WIDTH, HEIGHT, ARROW_COLORS, MOVE_SPEEDS, MOVE_DURATION, SCALE, XR_RADIUS, YH_RADIUS
from utils import draw_dashed_line, draw_text


class Arrow:
    def __init__(self, x, y, direction, is_player=False):
        self.original_x = WIDTH // 2
        self.original_y = HEIGHT // 2
        self.x = x
        self.y = y
        self.direction = direction
        self.is_player = is_player

        # 修改：动态计算4秒移动距离
        self.move_distance = MOVE_SPEEDS['advance'] * MOVE_DURATION * 60  # 速度 * 时间(秒) * 帧率(60fps)

        self.is_moving = False
        self.move_progress = 0
        self.is_returning = False
        self.return_speed = MOVE_SPEEDS['return']  # 使用配置的速度

        # 箭头尺寸
        rate = 0.7
        self.head_height = int(40 * rate)
        self.head_width = int(50 * rate)
        self.stem_width = int(12 * rate)
        self.stem_height = int(25 * rate)

        # 外观设置
        self.color = ARROW_COLORS['player'] if is_player else ARROW_COLORS['fixed']
        self.show_ring = False
        self.ring_radius = XR_RADIUS
        self.rotation = direction * 45  # 正北向为0

        self.highlight_timer = 0  # 新增：红圈计时器
        self.should_highlight = False  # 新增：是否显示红圈
        self.locked = False  # 新增：锁定状态（自动移动时不可控）
        self.events = {}  # 事件用

        self.twelve_group = 0  # 12控体分类： 0-不点名 1-烟火 2-悬刃
        self.visitable = True
        self.dashed_line_point = [0, 0]
        self._is_show_dashed_line = False

    def set_dashed_point(self, point):
        self.dashed_line_point = point

    def set_show_dashed_line(self, data: bool):
        self._is_show_dashed_line = data

    def clear_reg_circle(self):
        self.show_ring = False

    # 设置新角度
    def set_direction(self, direction):
        self.rotation = direction * 45

    def reg_move_event(self, event1, event2):
        self.events = {"begin": event1, "end": event2}

    def lock_movement(self):
        """锁定箭头（禁止玩家控制）"""
        self.locked = True

    def unlock_movement(self):
        """解锁箭头"""
        self.locked = False

    def start_highlight(self, duration):
        """启动红圈显示"""
        self.should_highlight = True
        self.highlight_timer = duration * 60  # 转换为帧数

    def toggle_ring(self):
        if self.is_player:
            self.show_ring = not self.show_ring

    # 瞬移到某一位置，以屏幕中心为原点
    def goto_with_scale_xy(self, x, y):
        self.x = int(WIDTH // 2 + x * SCALE)
        self.y = int(HEIGHT // 2 - y * SCALE)

    # 瞬移：极坐标，以屏幕中心为原点
    def goto_with_scale_polar(self, r, theta):
        radian = math.radians(theta)
        self.goto_with_scale_xy(r * math.cos(radian),
                                r * math.sin(radian))

    # 瞬移：极坐标，指定坐标为原点
    def goto_with_scale_polar_xy(self, x, y, r, theta):
        radian = math.radians(theta)
        self.goto_with_scale_xy(x + r * math.cos(radian),
                                y + r * math.sin(radian))

    def start_movement(self):
        """开始移动时重新计算距离（适应速度变化）"""
        if not self.is_moving and not self.is_returning:
            self.move_distance = MOVE_SPEEDS['advance'] * MOVE_DURATION * 60
            self.is_moving = True
            self.move_progress = 0
            self._set_begin_event()

    def return_to_center(self):
        """开始返回中心点"""
        self.is_returning = True
        self.is_moving = False  # 停止之前的移动

    def update_movement(self, move_speed):
        """使用配置的移动速度"""
        if self.is_moving:
            step = min(MOVE_SPEEDS['advance'], self.move_distance - self.move_progress)

            # 计算移动方向向量
            angle_rad = math.radians(self.rotation)
            dx = step * math.sin(angle_rad)
            dy = -step * math.cos(angle_rad)

            # 更新位置
            self.x += dx
            self.y += dy
            self.move_progress += step

            # 边界检查
            max_dim = max(self.head_height + self.stem_height, self.head_width)
            self.x = max(max_dim / 2, min(WIDTH - max_dim / 2, self.x))
            self.y = max(max_dim / 2, min(HEIGHT - max_dim / 2, self.y))

            # 检查是否完成移动
            if self.move_progress >= self.move_distance:
                self.is_moving = False
                self.move_progress = 0
                self._set_finish_event()

    def _set_begin_event(self):
        if self.events.__len__() == 2:
            pygame.time.set_timer(self.events["begin"], 1, 1)

    def _set_finish_event(self):
        if self.events.__len__() == 2:
            pygame.time.set_timer(self.events["end"], 1, 1)

    def update_return(self):
        """更新返回中心状态"""
        if self.is_returning:
            # 计算到中心点的距离
            dx = self.original_x - self.x
            dy = self.original_y - self.y
            distance = math.sqrt(dx ** 2 + dy ** 2)

            if distance <= self.return_speed:  # 已经足够接近
                self.x = self.original_x
                self.y = self.original_y
                self.is_returning = False
            else:
                # 标准化方向向量并乘以速度
                dx = dx / distance * self.return_speed
                dy = dy / distance * self.return_speed

                # 更新位置
                self.x += dx
                self.y += dy

    def update(self, move_speed):
        """更新红圈计时器"""
        if self.should_highlight:
            self.highlight_timer -= 1
            if self.highlight_timer <= 0:
                # 红圈消失
                self.should_highlight = False

        self.update_movement(move_speed)
        self.update_return()

    def get_points(self):
        # 原始未旋转的顶点（以(0,0)为中心）
        head_top = (0, -self.head_height - self.stem_height / 2)
        head_left = (-self.head_width / 2, -self.stem_height / 2)
        head_right = (self.head_width / 2, -self.stem_height / 2)

        stem_top_left = (-self.stem_width / 2, -self.stem_height / 2)
        stem_top_right = (self.stem_width / 2, -self.stem_height / 2)
        stem_bottom_left = (-self.stem_width / 2, self.stem_height / 2)
        stem_bottom_right = (self.stem_width / 2, self.stem_height / 2)

        # 旋转所有顶点
        angle_rad = math.radians(self.rotation)
        cos_val = math.cos(angle_rad)
        sin_val = math.sin(angle_rad)

        def rotate_point(x, y):
            return (x * cos_val - y * sin_val + self.x,
                    x * sin_val + y * cos_val + self.y)

        return (
            [rotate_point(*head_top), rotate_point(*head_right), rotate_point(*head_left)],
            [
                rotate_point(*stem_top_left), rotate_point(*stem_top_right),
                rotate_point(*stem_bottom_right), rotate_point(*stem_bottom_left)
            ]
        )

    def set_xr_circle(self):
        # 大圈
        self.ring_radius = XR_RADIUS

    def set_yh_circle(self):
        # 小圈
        self.ring_radius = YH_RADIUS

    # 原地不动起手
    def set_stand(self):
        self.twelve_group = 0

    # 烟火起手
    def _set_yh_begin(self):
        self.twelve_group = 1
        self.set_yh_circle()

    # 悬刃起手
    def _set_xr_begin(self):
        self.twelve_group = 2
        self.set_xr_circle()

    def set_twelve_group(self, group: int):
        if group == 1:
            self._set_yh_begin()
        elif group == 2:
            self._set_xr_begin()
        else:
            self.twelve_group = 0

    def switch_circle_size(self):
        if self.twelve_group == 1:
            self.set_xr_circle()
        elif self.twelve_group == 2:
            self.set_yh_circle()

    def draw(self, surface):
        if not self.visitable:
            return
        """绘制带红圈的箭头"""
        if self.should_highlight:
            pygame.draw.circle(
                surface, (255, 0, 0),
                (int(self.x), int(self.y)),
                int(self.ring_radius), 3
            )

        if self.show_ring and self.is_player:
            pygame.draw.circle(
                surface,
                (255, 0, 0),
                (int(self.x), int(self.y)),
                int(self.ring_radius),
                3  # 线宽
            )

        if self._is_show_dashed_line:
            # 绘制虚线并获取中点信息
            mid_point, length = draw_dashed_line(surface, (255, 0, 0), [self.x, self.y], self.dashed_line_point, 2, 30)

            # 绘制长度文本
            draw_text(surface, length, mid_point)

        head_points, stem_points = self.get_points()
        pygame.draw.polygon(surface, self.color, head_points)
        pygame.draw.polygon(surface, self.color, stem_points)

    def move(self, dx, dy):
        """重写移动方法，锁定状态下不可移动"""
        if not self.locked:
            if self.is_player:
                self.x += dx
                self.y += dy
                max_dim = max(self.head_height + self.stem_height, self.head_width)
                self.x = max(max_dim / 2, min(WIDTH - max_dim / 2, self.x))
                self.y = max(max_dim / 2, min(HEIGHT - max_dim / 2, self.y))
